package cn.wolfcode.luowowo.article.service.impl;

import cn.wolfcode.luowowo.article.domain.Community;
import cn.wolfcode.luowowo.article.domain.CommunityContent;
import cn.wolfcode.luowowo.article.mapper.CommunityContentMapper;
import cn.wolfcode.luowowo.article.mapper.CommunityMapper;
import cn.wolfcode.luowowo.article.query.CommunityQueryObject;
import cn.wolfcode.luowowo.article.service.ICommunityService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class CommunityServiceImpl implements ICommunityService {

    @Autowired
    private CommunityMapper communityMapper;

    @Autowired
    private CommunityContentMapper communityContentMapper;

    public void saveOrUpdate(Community community) {

        CommunityContent communityContent = community.getQuesContent();
        community.setCreatTime(new Date());

        String summary = communityContent.getContent();
        if (StringUtils.hasLength(summary)){
            if (summary.length() > 200){
                summary.substring(0, 200);
            }
        }
        community.setSummary(summary);
        if (community.getId() == null){
            communityMapper.insert(community);
            communityContent.setId(community.getId());
            //插入内容
            communityContentMapper.insert(communityContent);
        }else {
            communityMapper.updateByPrimaryKey(community);
        }
    }

    public PageInfo queryForList(CommunityQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<Community> list = communityMapper.queryForList(qo);
        return new PageInfo(list);
    }

    @Override
    public Community selectById(Long id) {
        CommunityContent content = communityContentMapper.selectByPrimaryKey(id);
        Community community = communityMapper.selectByPrimaryKey(id);
        community.setQuesContent(content);
        return community;
    }

    @Override
    public void updateNumyById(Long id) {

        communityMapper.updateNumyById(id);
    }
}
